<template>
  <view>
    <view v-if="!orderAddresInfoShow && !payOrderShow">
      <!-- 头部导航栏 -->
      <view class="top-navigate bg-yellow" style="padding: 53px 10px 20px 10px;">
        <navigator class="content cuIcon-back text-xl top-navigate-title" hover-class="none"
          url="../pick-send/pick-send" open-type="redirect">
        </navigator>
        <view class="text-xl top-navigate-title">订单</view>
      </view>
      <!-- 地图区域 -->
      <view class="page">
        <unicloud-map ref="map" :debug="false" loadtime="auto" collection="opendb-poi" :where="where" :width="750"
          :height="heightCom" :scale="25" :poi-maximum="100" :default-icon="defaultIcon" :custom-icons="customIcons"
          :enable-scroll="true" :enable-zoom="true" :show-compass="true" :show-location="true">
        </unicloud-map>
      </view>
      <!-- 订单信息区域 -->
      <view class="bottom-order-info" v-model="orderInfo">
        <!-- 帮我送地址区域 -->
        <view class="pick-send-address" v-if="TabCur== 0">
          <view class="address-now">
            <button class="cu-btn cuIcon bg-black">
              <text class="text-white">取</text>
            </button>
            <view class="address-text" @click="editeOrderStartInfo">
              <text class="text-df text-black text-cut" style="width: 250px;">{{address.name||'填写取件地址'}}</text>
              <text class="text-sm text-red">{{address.userName+address.phone||'填写联系人'}}</text>
            </view>
          </view>
          <view class="address-new" style=" margin-top: 10px;">
            <button class="cu-btn cuIcon bg-red">
              <text class="text-white">收</text>
            </button>
            <view class="address-text" @click="editeOrderEndInfo">
              <text class="text-df text-black text-cut" style="width: 250px;">{{addressEnd.name||'填写收件地址'}}</text>
              <text class="text-sm text-red">{{addressEnd.userName+addressEnd.phone ||'填写联系人'}}</text>
            </view>
          </view>
        </view>
        <!-- 帮我取地址区域 -->
        <view class="pick-send-address" v-else>
          <view class="address-new">
            <button class="cu-btn cuIcon bg-red">
              <text class="text-white">收</text>
            </button>
            <view class="address-text" @click="editeOrderEndInfo">
              <text class="text-df text-black text-cut" style="width: 250px;">{{addressEnd.name ||'填写收件地址'}}</text>
              <text class="text-sm text-red">{{addressEnd.userName+addressEnd.phone||'填写联系人'}}</text>
            </view>
          </view>
          <view class="address-now" style=" margin-top: 10px;">
            <button class="cu-btn cuIcon bg-black">
              <text class="text-white">取</text>
            </button>
            <view class="address-text" @click="editeOrderStartInfo">
              <text class="text-df text-black text-cut" style="width: 250px;">{{address.name || '填写取件地址'}}></text>
              <text class="text-sm text-red">{{address.userName+address.phone||'填写联系人'}}</text>
            </view>
          </view>
        </view>
        <!-- 物品信息选择展示区域 -->
        <view class="flex solid-bottom justify-between title" @click="showModal">
          <view class="cuIcon-goodsnew padding-sm margin-xs text-red"
            v-if="orderInfo.goodsInfo.goodsType==='' && orderInfo.goodsInfo.goodsWeight==='' ">请选择物品信息
          </view>
          <view class="cuIcon-goodsnew padding-sm margin-xs text-black" v-else>
            {{orderInfo.goodsInfo.goodsType}}/{{orderInfo.goodsInfo.goodsWeight}}公斤
          </view>
          <view class="cuIcon-right padding-sm margin-xs"></view>
        </view>
        <!-- 时间 -->
        <view class="cu-form-group">
          <view class="title">日期选择</view>
          <picker mode="date" :value="date" :start="date" :end="maxDate" @change="DateChange">
            <view class="picker">
              {{orderInfo.receiveTime.date || date}}
            </view>
          </picker>
        </view>
        <view class="cu-form-group">
          <view class="title">时间选择</view>
          <picker mode="time" :value="time" :start="time" end="24:00" @change="TimeChange">
            <view class="picker">
              {{orderInfo.receiveTime.time || time}}
            </view>
          </picker>
        </view>
        <!-- 备注 -->
        <view class="cu-form-group">
          <textarea maxlength="-1" @input="textareaAInput" placeholder="可备注物品描述,送检要求"
            v-model="orderInfo.note"></textarea>
        </view>
      </view>
      <!-- 服务协议 -->
      <view class="service-agreement">
        <checkbox class='round orange' :class="checkbox?'checked':''" :checked="checkbox?true:false" value="false"
          @click="CheckboxChange"></checkbox>
        <text class="text-gray service-txt">已阅读并同意《帮送服务协议》</text>
      </view>
      <!-- 购物车示例 -->
      <view ref="prgress1" class="cu-bar bg-white tabbar border shop foot">
        <view class="order-price">
          <view class="price-top">
            ￥ {{orderInfo.price || '—— ——'}}
          </view>
          <view class="price-bottom">
            {{orderInfo.distance||'填写地址后可查看'}}
          </view>
        </view>
        <view class="bg-red submit" @click="placeOrder">立即下单</view>
      </view>
      <!-- 底部隐藏的窗口 -->
      <view class="cu-modal bottom-modal" :class="modalName=='bottomModal'?'show':''">
        <view class="cu-dialog bg-white">
          <view class="cu-bar bg-white">
            <view class="action text-blue">选择物品信息</view>
            <view class="action text-green cuIcon-close" @tap="hideModal"></view>
          </view>
          <view class="padding-sm">
            <view class="tips text-sm padding-sm">
              请勿配送违禁品及价值5000元以上物品。如物品丢失或损坏，由配送服务提供方核查并处理，未保价物品最高赔付5倍跑腿费
            </view>
            <!-- 物品类型 -->
            <view class="types-title">
              物品类型
            </view>
            <view class="cu-list grid col-4 no-border">
              <view class="cu-item" v-for="(item,index) in goodsTypeList" :key="index" @click="selectGoodsType(item)">
                <view class="types-box " :class="orderInfo.goodsInfo.goodsType==item?'bg-orange cur':'bg-gray'">
                  {{item}}
                </view>
              </view>
            </view>
            <!-- 补充物品图片 -->
            <view class="goods-pic flex text-sm">
              <view class="cuIcon-pic text-orange margin-right">
                补充物品图
              </view>
              <view class="text-gray ">
                为匹配骑手，图片仅骑手可见
              </view>
            </view>
            <!-- 图片显示区域 -->
            <form>
              <view class="cu-form-group">
                <view class="grid col-4 grid-square flex-sub">
                  <view class="bg-img" v-for="(item,index) in tmpImgList" :key="index" @tap="ViewImage"
                    :data-url="item">
                    <image :src="item" mode="aspectFill" style="position: absolute;left:0"></image>
                    <!-- <view class="upload-progress" :style="'--percent:'+imgProgress">
                      <view class="progress-bar"></view>
                    </view> -->
                    <view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
                      <text class='cuIcon-close'></text>
                    </view>
                  </view>
                  <view class="solids" @tap="ChooseImage" v-if="tmpImgList.length<4">
                    <text class='cuIcon-cameraadd'></text>
                  </view>
                </view>
              </view>
            </form>
            <!-- 物品重量 -->
            <view class="cu-form-group">
              <view class="title">物品重量</view>
              <input class="input-weight" v-model="orderInfo.goodsInfo.goodsWeight" placeholder="超过5公斤,按每公斤1块钱计算"
                name="input"></input>
              <text class='text-orange'>公斤</text>
            </view>
            <!-- 确定下单 -->
            <button class="cu-btn round bg-orange margin-top confirm-goods-info" @click="confirmGoodsInfo">确认</button>
          </view>
        </view>
      </view>
    </view>
    <order-address-info v-if="orderAddresInfoShow"></order-address-info>
    <pay-order v-if="payOrderShow" :orderId="orderId" :price="price"></pay-order>
  </view>
</template>

<script>
  // import getDistance from '../../utils/getDistance.js'
  import {
    mapState,
    mapMutations
  } from 'vuex'
  var timer;
  const uniMapCo = uniCloud.importObject('uni-map-co', {
    customUI: true
  });
  const db = uniCloud.database();
  const _ = db.command;
  const category = "dynamics-001";
  var nowDate = new Date();
  //当前时间后三天
  var threeDayLate = new Date(nowDate.getTime() + 24 * 3600 * 1000 * 3);
  export default {
    data() {
      return {
        //订单信息
        orderInfo: {
          type:'代取送',
          userId: '',
          deliveryAddress: {},
          pickAddress: {},
          goodsInfo: {
            imgList: [],
            goodsType: '',
            goodsWeight: '',
          },
          receiveTime: {
            time: '',
            date: '',
          },
          //距离
          distance: '',
          note: '',
          price: 0
        },
        TabCur: 0,
        modalName: null,
        where: {
          category: category
        },
        defaultIcon: "/static/icon/logo.png", // 默认图标
        // 自定义图标
        customIcons: [{
            type: "配送员",
            icon: "/static/icon-3service/buy.png"
          },
          {
            type: "目的地",
            icon: "/static/icon-3service/buy.png"
          }
        ],
        isStart: false,
        polyline: [],
        isReady: false,
        //底部弹框物品类型列表
        goodsTypeList: ['餐饮', '文件', '生鲜', '蛋糕', '鲜花', '数码', '服饰', '快递', '其他'],
        index: -1,
        //订单地址信息表单
        orderAddresInfoShow: false,
        orderAddresInfoShowFlag: 0,
        //支付订单组件显示
        payOrderShow: false,
        remarkValue: '',
        //区别是否是下单页
        ifPlaceOrder: true,
        //服务协议checkbox
        checkbox: false,
        //当前下单的订单ID
        orderId: '',
        //图片上传进度样式
        imgProgress: 10,
        tmpImgList: [],
      }
    },
    onLoad(options) {
      this.orderInfo.userId = this.userinfo._id
      this.orderInfo.pickAddress = this.address
      this.orderInfo.deliveryAddress = this.addressEnd
      this.orderInfo.receiveTime.time = this.time
      this.orderInfo.receiveTime.date = this.date
      this.TabCur = options.TabCur
      if (this.address && this.addressEnd) return this.initData()

     
    },
    methods: {
      ...mapMutations('m_user', ['updateAddress']),
      // 显示底部弹框
      showModal(e) {
        this.modalName = 'bottomModal'
      },
      // 隐藏底部弹框
      hideModal(e) {
        this.goodsType = ''
        this.goodsWeight = ''
        this.modalName = null
      },
      async initData() {
        console.log('init');
        let res = await uniMapCo.initDynamics001({
          pickAddress: this.address,
          deliveryAddress: this.addressEnd
        });

        await this.refresh();

        this.setPolyline(res.polyline);
      },
      // 刷新地图
      async refresh() {
        await this.$refs.map.refresh({
          needIncludePoints: true
        });
        let res = await uniMapCo.getPolyline();
        //获取两地距离 res.distance
        this.orderInfo.distance = res.distance + '米';
        console.log(this.getDistance(this.address,this.addressEnd));
        if (res.end) {
          await this.$refs.map.refresh({
            needIncludePoints: true
          });
          this.stop();
          this.setPolyline([]);
        } else {
          this.setPolyline(res.polyline);
        }
      },
      // 设置路线
      setPolyline(polyline) {
        this.polyline = polyline;
        this.$refs.map.setPolyline(polyline);
      },
      // 停止监听
      stop() {
        this.isStart = false;
        if (timer) clearInterval(timer);
      },
      //上传图片操作
      async uploadImg() {
        var date = this.date;
        var time = this.time.replace(':', '-');
        // const that = this;    
        for (var i = 0; i < this.tmpImgList.length; i++) {
          let filePath = this.tmpImgList[i]
          //进行上传图片操作
          const result = await uniCloud.uploadFile({
            filePath: filePath,
            cloudPath: date + '-' + time + '-' + i + '.png',
            // onUploadProgress: function(progressEvent) {
            //   console.log(progressEvent);
            //   var percentCompleted = Math.round(
            //     (progressEvent.loaded * 100) / progressEvent.total
            //   );
            //   that.imgProgress=percentCompleted
            // },
          });
          this.orderInfo.goodsInfo.imgList.push(result.fileID)
          // console.log(result);
        }
      },
      //选择图片相关操作
      ChooseImage() {
        uni.chooseImage({
          count: 4, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album'], //从相册选择
          success: (res) => {
            console.log(res);
            if (this.tmpImgList.length != 0) {
              this.tmpImgList = this.tmpImgList.concat(res.tempFilePaths)
            } else {
              this.tmpImgList = res.tempFilePaths
            }
          }
        });
      },
      ViewImage(e) {
        uni.previewImage({
          urls: this.tmpImgList,
          current: e.currentTarget.dataset.url
        });
      },
      DelImg(e) {
        uni.showModal({
          title: this.userinfo.user_name,
          content: '确定要删除这张物品图片吗？',
          cancelText: '取消',
          confirmText: '确定',
          success: res => {
            if (res.confirm) {
              this.tmpImgList.splice(e.currentTarget.dataset.index, 1)
            }
          }
        })
      },
      //选择物品信息 确认按钮事件
      confirmGoodsInfo() {
        if (this.orderInfo.goodsInfo.goodsType === '') return uni.$showMsg('请选择商品类型！')
        if (this.orderInfo.goodsInfo.goodsWeight === '') return uni.$showMsg('请添加商品重量！')
        this.modalName = null
        this.orderInfo.price = this.orderPrice
      },
      //选择物品类型事件
      selectGoodsType(item) {
        this.orderInfo.goodsInfo.goodsType = item
      },
      //编辑送取货订单起点位置信息
      editeOrderStartInfo() {
        this.orderAddresInfoShowFlag = 1
        this.orderAddresInfoShow = true
      },
      //编辑送取货订单终点位置信息
      editeOrderEndInfo() {
        this.orderAddresInfoShowFlag = 2
        this.orderAddresInfoShow = true
      },
      textareaAInput(e) {
        this.remarkValue = e.detail.value
      },
      TimeChange(e) {
        this.orderInfo.receiveTime.time = e.detail.value
      },
      DateChange(e) {
        this.orderInfo.receiveTime.date = e.detail.value
      },
      //服务协议点击更改勾选事件
      CheckboxChange() {
        this.checkbox = !this.checkbox
      },
      //下单 添加订单事件回调
      async placeOrder() {
        if (this.orderInfo.goodsInfo.goodsType === '' || this.orderInfo.goodsInfo.goodsWeight === '') return this
          .showModal()
        if (!this.checkbox) return uni.$showMsg('请先同意服务协议')
        //满足下单要求 将订单信息图片上传
        if(this.tmpImgList) await this.uploadImg();
        
        console.log(this.orderInfo);
        const {
          result: res
        } = await db.collection("my_order").add(this.orderInfo)
        //根据订单id 携带到子组件 支付订单
        this.orderId = res.id
        console.log('订单id：', this.orderId);
        if (res.id) {
          this.payOrderShow = true
          return uni.$showMsg('下单成功！')
        }
      },
      getDistance(l1,l2) {
        var radLat1 = (l1.latitude * Math.PI) / 180; //将角度换算为弧度
        var radLat2 = (l2.latitude * Math.PI) / 180; //将角度换算为弧度
        var a = radLat1 - radLat2;
        var b = (l1.longitude * Math.PI) / 180 - (l2.longitude * Math.PI) / 180;
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(
          Math.sin(b / 2), 2)));
        s = s * 6378137.0; // 取WGS84标准参考椭球中的地球长半径(单位:m)
        //s = Math.round(s * 10000) / 10000; //两点之间距离(保留四位)
        return s; //(单位:m)
      }
    },
    computed: {
      ...mapState('m_user', ['userinfo', 'address', 'addressEnd']),
      //地图高度属性
      heightCom() {
        let systemInfo = uni.getSystemInfoSync();
        return `${systemInfo.windowHeight *(3/5)}px`;
      },
      //订单费用
      orderPrice() {
        if (this.orderInfo.goodsInfo.goodsWeight === '') return null
        if (this.orderInfo.goodsInfo.goodsWeight <= 5) {
          return 2
        } else {
          return Number((2 + ((this.orderInfo.goodsInfo.goodsWeight - 5) * 1.2)).toFixed(2))
        }
      },
      date() {
        return nowDate.getFullYear() + "-" + (nowDate.getMonth() + 1) + "-" + nowDate.getDate()
      },
      maxDate() {
        return threeDayLate.getFullYear() + "-" + (threeDayLate.getMonth() + 1) + "-" + threeDayLate.getDate()
      },
      time() {
        return nowDate.getHours() + ":" + nowDate.getMinutes()
      },
      //订单的price
      price() {
        return this.orderInfo.price
      },

    },
    watch: {
      address: {
        handler: function(newValue, oldValue) {
          this.orderInfo.pickAddress = this.address
          if (this.address && this.addressEnd) return this.initData()
        },
      },
      addressEnd(newValue, oldValue) {
        this.orderInfo.deliveryAddress = this.addressEnd
        if (this.address && this.addressEnd) return this.initData()
      },
    },
  }
</script>

<style lang="scss">
  .top-navigate {
    z-index: !important;
    position: relative;
    display: flex;
    justify-content: left;
    align-items: center;

    .top-navigate-title {
      margin: 0 5px;
      font-weight: bold;
    }
  }

  .tips {
    border-radius: 10px;
    background-color: #FEF8E8;
  }

  .types-title {
    display: flex;
    justify-content: left;
    color: black;
    font-size: 30rpx;
    margin: 5px 10rpx;
    font-weight: 700;
  }

  .types-box {
    border-radius: 5px;
    width: 70px;
    height: 40px;
    line-height: 40px;
    margin: 0 auto;
  }

  .goods-pic {
    margin: 15px 10rpx;
  }

  .title {
    font-weight: 700;
    color: black;
  }

  .input-weight {
    text-align: left;
  }

  .confirm-goods-info {
    height: 35px;
    width: 95%;
    margin: 10px auto;
  }

  /*订单信息表*/
  .bottom-order-info {
    position: relative;
    margin: 0 auto;
    background-color: white;
    padding: 5px;
    border-radius: 10px;
    width: 95%;
    top: -100px;
    bottom: 0;
    left: 0;

    .pick-send-address {
      margin: 10px;
      border-bottom: 1px #efefef solid;

      .address-now,
      .address-new {
        height: 50px;
        display: flex;
        justify-content: left;
        align-items: center;

        .address-text {
          margin-left: 20px;
          display: flex;
          flex-direction: column;

        }
      }

      .address-new {
        height: 50px;
        border-radius: 10px;
        background-color: #efefef;
        display: flex;
        justify-content: left;
        align-items: center;
      }
    }
  }

  .service-agreement {
    position: relative;
    margin: 0 auto;
    width: 95%;
    top: -90px;
    display: flex;
    align-items: center;

    .service-txt {
      margin-left: 10px;
      font-size: 14px;
    }
  }

  .order-price {
    text-align: center;
    flex: 3.4;
  }

  .cuIcon {
    width: 50rpx;
    height: 50rpx;
    border-radius: 500rpx;
    padding: 0;
    margin-left: 10rpx;
  }

  .goods-info-show {
    display: flex;
    flex: 1;
    align-items: center;
  }

  .cuIcon-goodsnew::before {
    margin-right: 10px;
  }

  .upload.progress .upload-progress {
    display: block;
  }

  //图片上传
  .upload-progress {
    background: #00000080;
  }

  .progress-bar {
    position: absolute;
    width: 90%;
    height: 3px;
    background: #fff;
    border-radius: 3px;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    color: #fff;
    font-size: 12px;
  }

  .progress-bar::before {
    counter-reset: progress var(--percent);
    content: counter(progress) '%';
    position: absolute;
    left: 50%;
    top: -20px;
    transform: translateX(-50%);
  }

  .progress-bar::after {
    content: '';
    position: absolute;
    left: 0;
    border-radius: inherit;
    width: calc(1% * var(--percent));
    height: 100%;
    background: var(--primary-color);
  }

  .upload-progress::after {
    content: '文件上传中...';
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, 5px);
    white-space: nowrap;
    opacity: 0.8;
    color: #fff;
    font-size: 12px;
  }
</style>